package com.geeke.utils;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import com.alibaba.fastjson.JSONObject;
import com.geeke.sys.entity.User;


/**
 * 用户工具类
 * @author lys
 * @version 2018-12-05
 */
public class SessionUtils {

	// user线程变量，用于定时任务保存用户
	private static ThreadLocal<User> threadLocalUser = new ThreadLocal<User>();

	/**
     * session中存放用户信息的key值
     */
    private static final String SESSION_USER_INFO = "userInfo";
    private static final String SESSION_USER_PERMISSION = "userPermission";
	private static final String SESSION_YEWECHAT_OPENID = "openId";

	/**
	 * 获取session保存的用户信息
	 * @return 
	 */
	public static User getUser(Session session){
		JSONObject jsonUser = (JSONObject)session.getAttribute(SESSION_USER_INFO);
		if(jsonUser == null) {
			return null;
		}
		return jsonUser.toJavaObject(User.class);
	}

	/**
	 * 获取当前用户
	 * @return 
	 */
	public static User getUser(){
		Subject subject = ThreadContext.getSubject();
		// subject为null时，定时等非shiro访问过来的
		if(subject == null) {
			return threadLocalUser.get();
		} else {
			return getUser(subject.getSession());
		}
	}
	
	
    /**
	 * 设置当前用户
	 * @return
	 */
	public static void setUser(User user){
		Subject subject = ThreadContext.getSubject();
		// subject为null时，定时等非shiro访问过来的
		if(subject == null) {
			threadLocalUser.set(user);
		} else {
			Object jsonUser = JSONObject.toJSON(user);
			subject.getSession().setAttribute(SESSION_USER_INFO, jsonUser);
		}
	}

	@SuppressWarnings("unchecked")
	public static List<String> getUserPermission() {
		return (List<String>)SecurityUtils.getSubject().getSession().getAttribute(SESSION_USER_PERMISSION);
	}
	
	public static void setUserPermission(List<String> permissionList) {
		SecurityUtils.getSubject().getSession().setAttribute(SESSION_USER_PERMISSION, permissionList);
	}

	/**
	 * 获取企业微信当前用户
	 * @return 取不到返回 JSONObject
	 */
	public static JSONObject getWeChatUser(){
		return (JSONObject)SecurityUtils.getSubject().getSession().getAttribute(SESSION_YEWECHAT_OPENID);
	}


	/**
	 * 设置企业微信当前用户
	 * @return
	 */
	public static void setWeChatUser(JSONObject jsonObject){
		SecurityUtils.getSubject().getSession().setAttribute(SESSION_YEWECHAT_OPENID, jsonObject);
	}
	
}
